package com.newenergy.wisehome.ui.fragment;


import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.ToastUtil;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.BathHeater;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.ElectricHeater;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.FamilyUnique;
import com.newenergy.wisehome.data.bean.Fan;
import com.newenergy.wisehome.data.bean.FanLamp;
import com.newenergy.wisehome.data.bean.HealthBasin;
import com.newenergy.wisehome.data.bean.SecneMode;
import com.newenergy.wisehome.data.ormlite.dao.BLDeviceInfoDao;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.BathHeaterDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.data.ormlite.dao.ElectricHeaterDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyUniqueDao;
import com.newenergy.wisehome.data.ormlite.dao.FanDao;
import com.newenergy.wisehome.data.ormlite.dao.FanLampDao;
import com.newenergy.wisehome.data.ormlite.dao.HealthBasinDao;
import com.newenergy.wisehome.data.ormlite.dao.SecneGroupDao;
import com.newenergy.wisehome.data.ormlite.dao.SecneModeDao;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.adapter.FramilyAdapter;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.weyye.hipermission.HiPermission;
import me.yokeyword.fragmentation.ISupportFragment;


/**
 * 家庭列表
 */
public class FramliyFragment extends BaseFragment {

    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;

    @BindView(R.id.tv_empty)
    TextView mTvEmpty;
    @BindView(R.id.btn_add)
    Button mBtnAdd;

    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    @BindView(R.id.btn_add_framily)
    Button mBtnAddFramily;
    @BindView(R.id.btn_edit)
    Button mBtnEdit;
    @BindView(R.id.rl_empty)
    RelativeLayout mRlEmpty;


    private FramilyAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private int mcurrPosition = 0;
    private Family mCurrFamily;
    private boolean checkPermission = false;
    private Dialog mDialog;
    private int confirType = 0;//此处0代表不跳转，2代表确认的时候跳转到设置界面
    private TextView mTv_tip;

    public FramliyFragment() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_framliy;
    }


    public static ISupportFragment newInstance() {
        return new FramliyFragment();
    }


    @Override
    public void init(View rootView) {
        initRecycleView();
    }

    @Override
    public void onResume() {
        super.onResume();
        mTvPage.setText(getString(R.string.family_list));
        mTvEmpty.setText(getString(R.string.tip_please_add_family));
        refreshData();
        boolean b = HiPermission.checkPermission(getActivity(), Manifest.permission.CAMERA);
        if (checkPermission) {
            if (b) {
                startActivityForResult(new Intent(getActivity(), CaptureActivity.class), 1000);
                mDialog.dismiss();
                checkPermission = false;
            } else {
                ToastUtil.toast(getString(R.string.no_camera_permission));
            }
        }
    }

    private void refreshData() {
        FamilyDao familyDao = new FamilyDao(getContext());
        mAdapter.refreshData(familyDao.getAll());
        showEmptyView();
        setCurrentItem();
    }

    public void showEmptyView() {
        boolean empty = false;
        if (mAdapter.getAllData().size() < 1) {
            empty = true;
        }

        mRlEmpty.setVisibility(empty ? View.VISIBLE : View.GONE);
        mRecyclerView.setVisibility(empty ? View.GONE : View.VISIBLE);
    }

    private void setCurrentItem() {
        String familyId = SPUtil.getString("FAMILY_ID", "12345678");
        List<Family> datas = mAdapter.getAllData();
        if (datas.size() < 1) {
            mBtnAdd.setVisibility(View.INVISIBLE);
            AppManager.getInstance(getContext()).mCurrFamily = null;
            return;
        }
        mBtnAdd.setVisibility(View.VISIBLE);
        mBtnAdd.setBackgroundResource(R.drawable.btn_edit_n);
        setCurrPosition(familyId);
        updateCurrFamily();
    }

    private void setCurrPosition(String familyId) {
        List<Family> datas = mAdapter.getAllData();
        if (datas.size() < 1) return;
        int i = 0;
        for (Family framily : datas) {
            if (familyId.equals(framily.getFamilyId())) {
                mcurrPosition = i;
            }
            i++;
        }
    }

    private void updateCurrFamily() {
        List<Family> datas = mAdapter.getAllData();
        if (datas.size() < 1) return;
        for (Family framily : datas) {
            framily.setChecked(false);
        }
        if (mcurrPosition >= datas.size()) {
            mcurrPosition = 0;
        }
        mCurrFamily = datas.get(mcurrPosition);
        mCurrFamily.setChecked(true);
        BLLocalFamilyManager.getInstance().setCurrFamily(mCurrFamily);
        AppManager.getInstance(getContext()).mCurrFamily = mCurrFamily;

        BallLight ballLight = new BallLight(mCurrFamily.getFamilyId(), 1, "00", getString(R.string.all_device), "suo you deng", "bg_all_device_n");
        AppManager.getInstance(getContext()).mAllGroup = ballLight;

        if (mCurrFamily.getFamilyId().equals("12345678")) {
            mBtnAdd.setVisibility(View.GONE);
        } else {
            mBtnAdd.setVisibility(View.VISIBLE);
        }

        mAdvertiserManager.mSeed = mCurrFamily.getSeed();
        mAdvertiserManager.mFeedBack = mCurrFamily.getFeedback();
        SPUtil.put("FAMILY_ID", mCurrFamily.getFamilyId());
        mAdapter.notifyDataSetChanged();
    }


    private void initRecycleView() {
        Context context = getContext().getApplicationContext();
        mAdapter = new FramilyAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter.setOnItemClickListener(position -> {
            mcurrPosition = position;
            AppManager.getInstance(getContext()).mGroupIndex = 0;
            AppManager.getInstance(getContext()).mHEAIndex = 0;
            updateCurrFamily();
        });

    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_add, R.id.btn_add_framily})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_add:
                showEditDialog();
                break;

            case R.id.btn_add_framily:
                showBottomDialog();
                break;

        }
    }


    private void showEditDialog() {
        final Dialog dialog = new Dialog(getContext(), R.style
                .style_dialog);
        View contentView = View.inflate(getContext(), R.layout
                .dialog_edit_family, null);
        dialog.setContentView(contentView);
        EditText et_name = (EditText) contentView.findViewById(R.id
                .et_name);
        Button btn_delete = (Button) contentView.findViewById(R.id
                .btn_delete);
        btn_delete.setVisibility(View.VISIBLE);
        Button btn_confirm = (Button) contentView.findViewById(R.id
                .btn_confirm);
        Button btn_cancel = (Button) contentView.findViewById(R.id
                .btn_cancel);

        mTv_tip = (TextView) contentView.findViewById(R.id
                .tv_tip);

        String groupName = mCurrFamily.getName();
        et_name.setText(groupName);
        et_name.setSelection(groupName.length());

        dialog.show();


        //删除家庭
        btn_delete.setOnClickListener(v -> {
            String mag = getString(R.string.sure_delete) + mCurrFamily.getName() + getString(R.string.delete_will_lost);
            confirType = 1;
            showConfirmDialog(mag);
            dialog.dismiss();
        });


        //修改家庭名称
        btn_confirm.setOnClickListener(v -> {
            String name = et_name.getText().toString().trim();
            /*boolean isOk = checkFamilyName(name);
            if (!isOk) return;*/

            FamilyDao familyDao = new FamilyDao(getContext());
            if (TextUtils.isEmpty(name)) {
//                ToastUtil.myToast(getString(R.string.tip_family_name_nonull), true);
                mTv_tip.setText(getString(R.string.tip_family_name_nonull));
                return;
            }

            if (LocaleUtil.getLanguage().startsWith("zh")) {
                if (name.length() < 2 || name.length() > 5) {
//                    ToastUtil.myToast(getString(R.string.tip_family_name_range), true);
                    mTv_tip.setText(getString(R.string.tip_family_name_range));
                    return;
                }
            } else {
                if (name.length() < 1) {
//                    ToastUtil.myToast(getString(R.string.tip_family_name_range), true);
                    mTv_tip.setText(getString(R.string.tip_family_name_range));
                    return;
                }
            }


            if (name.contains("[") || name.contains("#") || name
                    .contains("&")) {
//                ToastUtil.myToast(getString(R.string.tip_family_name_error), true);
                mTv_tip.setText(getString(R.string.tip_family_name_error));
                return;
            }
            List<Family> families = familyDao.getAll();
            for (Family family : families) {
                if (family.getName().equals(name)) {
//                    ToastUtil.myToast(getString(R.string.tip_family_name_used), true);
                    mTv_tip.setText(getString(R.string.tip_family_name_used));
                    return;
                }
            }
            mCurrFamily.setName(name);
            familyDao.updateFamily(mCurrFamily);
            refreshData();
            BLLocalFamilyManager.getInstance().updateBLFamilyName(mCurrFamily);


            dialog.dismiss();
        });
        btn_cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
    }


    public void showBottomDialog() {
        View contenView = View.inflate(getContext(), R.layout.dialog_add_framily, null);

        mDialog = new Dialog(getContext(), R.style.style_dialog);

        Window window = mDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

        Button addFramily = (Button) contenView.findViewById(R.id
                .btn_add_framily);
        Button scanQrCode = (Button) contenView.findViewById(R.id
                .btn_scan_qrcode);
        Button cancel = (Button) contenView.findViewById(R.id
                .btn_cancel);

        mDialog.setContentView(contenView);

        mDialog.show();

        addFramily.setOnClickListener(v -> {
            mDialog.dismiss();
            showAddDialog();
        });
        scanQrCode.setOnClickListener(v -> {
            setScanStatus(mDialog);

        });
        cancel.setOnClickListener(v -> {
            mDialog.dismiss();
        });

    }


    private void setScanStatus(Dialog dialog) {
        boolean b = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            b = HiPermission.checkPermission(getActivity(), Manifest.permission.CAMERA);

        } else {
            b = PermissionChecker.checkSelfPermission(mainActivity, Manifest.permission.CAMERA)
                    == PermissionChecker.PERMISSION_GRANTED;
        }

        if (b) {
            dialog.dismiss();
            startActivityForResult(new Intent(getActivity(),
                    CaptureActivity.class), 1000);
        } else {
            confirType = 2;
            showConfirmDialog(getString(R.string.open_camera_permission));
        }

    }


    private void showAddDialog() {
        final Dialog dialog = new Dialog(getContext(), R.style.style_dialog);

        View contentView = View.inflate(getContext(), R.layout.dialog_edit_family, null);
        dialog.setContentView(contentView);
        EditText et_name = (EditText) contentView.findViewById(R.id.et_name);

        Button btn_confirm = (Button) contentView.findViewById(R.id.btn_confirm);

        Button btn_cancel = (Button) contentView.findViewById(R.id.btn_cancel);
        mTv_tip = (TextView) contentView.findViewById(R.id.tv_tip);


        dialog.show();

        btn_confirm.setOnClickListener(v -> {
            String name = et_name.getText().toString().trim();

           /* boolean isOk = checkFamilyName(name);
            if (!isOk) return;*/
            FamilyDao familyDao = new FamilyDao(getContext());
            if (TextUtils.isEmpty(name)) {
//                ToastUtil.myToast(getString(R.string.tip_family_name_nonull), true);
                mTv_tip.setText(getString(R.string.tip_family_name_nonull));
                return;
            }

            if (LocaleUtil.getLanguage().startsWith("zh")) {
                if (name.length() < 2 || name.length() > 5) {
//                    ToastUtil.myToast(getString(R.string.tip_family_name_range), true);
                    mTv_tip.setText(getString(R.string.tip_family_name_range));
                    return;
                }
            } else {
                if (name.length() < 1) {
//                    ToastUtil.myToast(getString(R.string.tip_family_name_range), true);
                    mTv_tip.setText(getString(R.string.tip_family_name_range));
                    return;
                }
            }
            if (name.contains("[") || name.contains("#") || name
                    .contains("&")) {
//                ToastUtil.myToast(getString(R.string.tip_family_name_error), true);
                mTv_tip.setText(getString(R.string.tip_family_name_error));
                return;
            }
            List<Family> families = familyDao.getAll();
            for (Family family : families) {
                if (family.getName().equals(name)) {
//                    ToastUtil.myToast(getString(R.string.tip_family_name_used), true);
                    mTv_tip.setText(getString(R.string.tip_family_name_used));
                    return;
                }
            }
            FamilyUniqueDao uniqueDao = new FamilyUniqueDao(getContext());
            FamilyUnique unique = uniqueDao.getByType(0);
            if (unique == null) {
                mTv_tip.setText(getString(R.string.no_home_code_available));
//                myToast(getString(R.string.no_home_code_available), false);
                return;
            }
            unique.setType(1);
            uniqueDao.update(unique);

            String familyId = unique.getFamilyId();
            LogHelper.i("创建新家庭码=" + familyId);

            int seed = unique.getSeed();
            int feedBack = unique.getFeedback();

            Family family = new Family(familyId, name, 3, seed, feedBack);
            family.setType(1);
            family.setChecked(true);

            BallLightDao ballLightDao = new BallLightDao(getContext());
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());

            familyDao.add(family);
            SPUtil.put("FAMILY_ID", familyId);

            mAdapter.add(family);
            //使新建的家庭位于当前选中的状态
            mcurrPosition = mAdapter.getAllData().size() - 1;
            AppManager.getInstance(getContext()).mGroupIndex = 0;
            AppManager.getInstance(getContext()).mHEAIndex = 0;
            refreshData();

            //添加默认的五个房间、使用新的家庭码
            String scenedata1 = familyId + "01" + "FF000000" + "FFFFFF";
            String scenedata2 = familyId + "02" + "FF000000" + "FFFFFF";
            String scenedata3 = familyId + "03" + "FF000000" + "FFFFFF";
            String scenedata4 = familyId + "04" + "FF000000" + "FFFFFF";
            String scenedata5 = familyId + "05" + "FF000000" + "FFFFFF";
            BallLight ballLight1 = new BallLight(familyId, 1, "01", getString(R.string.master_bedroom), "zhu wo", "btn_balllight", scenedata1);
            BallLight ballLight2 = new BallLight(familyId, 1, "02", getString(R.string.second_bedroom), "ci wo", "btn_balllight", scenedata2);
            BallLight ballLight3 = new BallLight(familyId, 1, "03", getString(R.string.kitchen), "chu fang", "btn_balllight", scenedata3);
            BallLight ballLight4 = new BallLight(familyId, 1, "04", getString(R.string.living_room), "ke ting", "btn_balllight", scenedata4);
            BallLight ballLight5 = new BallLight(familyId, 1, "05", getString(R.string.restaurant), "can ting", "btn_balllight", scenedata5);
            ballLightDao.add(ballLight1);
            ballLightDao.add(ballLight2);
            ballLightDao.add(ballLight3);
            ballLightDao.add(ballLight4);
            ballLightDao.add(ballLight5);
            DeviceCategory deviceCategory1 = ballLight1.covertToDeviceCategory();
            DeviceCategory deviceCategory2 = ballLight2.covertToDeviceCategory();
            DeviceCategory deviceCategory3 = ballLight3.covertToDeviceCategory();
            DeviceCategory deviceCategory4 = ballLight4.covertToDeviceCategory();
            DeviceCategory deviceCategory5 = ballLight5.covertToDeviceCategory();
            deviceCategoryDao.add(deviceCategory1);
            deviceCategoryDao.add(deviceCategory2);
            deviceCategoryDao.add(deviceCategory3);
            deviceCategoryDao.add(deviceCategory4);
            deviceCategoryDao.add(deviceCategory5);

            BallLight ballLight = new BallLight(familyId, 1, "00", getString(R.string.all_device), "suo you deng", "bg_all_device_n");
            AppManager.getInstance(getContext()).mAllGroup = ballLight;
            dialog.dismiss();
        });
        btn_cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
    }



    @Override
    protected void confirmOperation() {
        if (confirType == 1) {
            deleteFamily();
        }
        if (confirType == 2) {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", mainActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", mainActivity.getPackageName());
            }
            startActivity(localIntent);
            checkPermission = true;
        }
    }

    private void deleteFamily() {
        BLLocalFamilyManager blFamilyManager = BLLocalFamilyManager.getInstance();
        blFamilyManager.delBLFamily(mCurrFamily);
        String familyId = mCurrFamily.getFamilyId();
        delFamilyBlDevices(mCurrFamily);
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> familyDeviceCategorys = deviceCategoryDao.getFamilyDeviceCategorys(familyId);

        deviceCategoryDao.delete(familyDeviceCategorys);

        BallLightDao ballLightDao = new BallLightDao(getContext());
        List<BallLight> groups = ballLightDao.getFamilyBallLights(familyId, 1);
        ballLightDao.delete(groups);

        FanDao fanDao = new FanDao(getContext());
        List<Fan> fans = fanDao.getFamilyFans(familyId, 2);
        fanDao.delete(fans);

        FanLampDao fanLampDao = new FanLampDao(getContext());
        List<FanLamp> fanLamps = fanLampDao.getFamilyFanLamps(familyId, 3);
        fanLampDao.delete(fanLamps);

        ElectricHeaterDao electricHeaterDao = new ElectricHeaterDao(getContext());
        List<ElectricHeater> electricHeaters = electricHeaterDao.getFamilyElectricHeaters(familyId, 4);
        electricHeaterDao.delete(electricHeaters);

        BathHeaterDao bathHeaterDao = new BathHeaterDao(getContext());
        List<BathHeater> bathHeaters = bathHeaterDao.getFamilyBathHeaters(familyId, 5);
        bathHeaterDao.delete(bathHeaters);

        HealthBasinDao healthBasinDao = new HealthBasinDao(getContext());
        List<HealthBasin> healthBasins = healthBasinDao.getFamilyHealthBasins(familyId, 9);
        healthBasinDao.delete(healthBasins);

        FamilyDao familyDao = new FamilyDao(getContext());
        SecneModeDao secneModeDao = new SecneModeDao(getContext());
        SecneGroupDao secneGroupDao = new SecneGroupDao(getContext());

        String fid = mCurrFamily.getFamilyId();
        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(getContext());
        uniqueDao.setTypeWithUnique(fid, 0);
        familyDao.delete(mCurrFamily);
        String msg = getString(R.string.delete) + mCurrFamily.getName() + getString(R.string.success);
        AppManager.getInstance(getContext()).mGroupIndex = 0;
        AppManager.getInstance(getContext()).mHEAIndex = 0;
//        updateCurrFamily();
        refreshData();
        ToastUtil.myToast(msg, false);
        List<SecneMode> secneModes = secneModeDao.getFamilySecnes(familyId);
        for (SecneMode secneMode : secneModes) {
            int id = secneMode.getId();
            secneGroupDao.deleteSecneMode(id);
        }
        secneModeDao.delete(secneModes);

    }

    private void delFamilyBlDevices(Family family) {
        if (family == null || TextUtils.isEmpty(family.getBlFamilyId())){
            return;
        }
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(getContext());
        String familyId = family.getFamilyId();
        deviceInfoDao.deleteFamilyBLDeviceInfos(familyId);
    }


    public static long bytes2long(byte[] b) {
        long temp = 0;
        long res = 0;
        for (int i = 0; i < 8; i++) {
            res <<= 8;
            temp = b[i] & 0xff;
            res |= temp;
        }
        return res;
    }

}
